package archer.framework.utils;

import archer.framework.core.exception.BaseException;
import jodd.bean.BeanCopy;
import jodd.bean.BeanUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author christ
 * @date 2016/9/30
 */
public class BeanUtils {

    public static BeanUtil pojo = BeanUtil.pojo;

    public static BeanUtil declared = BeanUtil.declared;

    /**
     * bean copy
     *
     * @param src
     * @param targetClass
     */
    public static <T> T copy(Object src, Class<T> targetClass) {
        T target = newInstance(targetClass);
        BeanCopy.from(src).to(target).copy();
        return target;
    }

    public static <T> List<T> copy(List src, Class<T> targetClass) {
        List<T> results = new ArrayList<T>();
        for (Object each : src) {
            results.add(copy(each, targetClass));
        }
        return results;
    }


    private static <T> T newInstance(Class<T> clazz) {
        try {
            return (T) ReflectUtils.newInstance(clazz);
        } catch (Exception e) {
            throw new BaseException(e);
        }
    }
}
